﻿using System.IO;
using System.Linq;
using FileSynchronizer.DataAccess;

namespace FileSynchronizer.Objects
{
    public static class SyncFolderPairHelper
    {
        #region Public variables and properties
        //---------------------------------------------------------------------------------------------------------------------------------------
        // Check if the new FolderPair is not included in previous FolderPairs
        //---------------------------------------------------------------------------------------------------------------------------------------
        public static bool IsValidFolderPair(IQueryable<FolderPair> TheFolderPairs,  string NewLeftFolder, string NewRightFolder)
        {
            bool TheResult = true;


            string ExistingLeftFolder = "";
            string ExistingRightFolder = "";

            if (TheFolderPairs != null)
            {
                foreach (FolderPair theFolderPair in TheFolderPairs)
                {
                    ExistingLeftFolder = theFolderPair.LeftFolder;
                    ExistingRightFolder = theFolderPair.RightFolder;

                    if (!Directory.Exists(ExistingLeftFolder))
                    {
                        TheResult = false;
                        break;
                    }
                    if (!Directory.Exists(ExistingRightFolder))
                    {
                        TheResult = false;
                        break;
                    }
                    if (NewLeftFolder.StartsWith(ExistingLeftFolder) |
                        NewLeftFolder.StartsWith(ExistingRightFolder) |
                        NewLeftFolder.StartsWith(NewRightFolder))
                    {
                        TheResult = false;
                        break;
                    }

                    if (NewRightFolder.StartsWith(ExistingRightFolder) |
                        NewRightFolder.StartsWith(ExistingLeftFolder) |
                        NewRightFolder.StartsWith(NewLeftFolder))
                    {
                        TheResult = false;
                        break;
                    }

                    if (ExistingLeftFolder.StartsWith(NewLeftFolder) |
                        ExistingLeftFolder.StartsWith(NewRightFolder))
                    {
                        TheResult = false;
                        break;
                    }

                    if (ExistingRightFolder.StartsWith(NewRightFolder) |
                        ExistingRightFolder.StartsWith(NewLeftFolder))
                    {
                        TheResult = false;
                        break;
                    }
                }
            }
            return TheResult;
        }
        //---------------------------------------------------------------------------------------------------------------------------------------
        #endregion
    
    }
}
